package common.store.web.controller;


import common.store.common.util.MD5;
import common.store.web.bean.User;
import common.store.common.util.C3p0Pool;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.UUID;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req , resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        System.out.println(req.getParameter("username"));
        String password = MD5.stringMD5(req.getParameter("password"));

        User user = new User();
        try {
            BeanUtils.populate(user , req.getParameterMap());
            user.setUid(UUID.randomUUID().toString().replaceAll("-",""));
            user.setPassword(password);
            user.setState(0);
            QueryRunner qr = new QueryRunner(C3p0Pool.getDataSource());

            String sql = "insert into user values(?,?,?,?,?,?,?,?,?,?)";
            int rows = qr.update(sql , user.getUid() , user.getUsername()
                    , user.getPassword() , user.getName() , user.getEmail()
                    , user.getTelephone() , user.getBirthday()
                    , user.getSex() , user.getState() , user.getCode());

            if(rows > 0){
                resp.sendRedirect(req.getContextPath() + "/login.jsp");
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
